import React, { useState } from 'react'
import { Card, Input ,Spin, Button, message } from 'antd';
import 'antd/dist/antd.css'
import { UserOutlined, KeyOutlined } from '@ant-design/icons'
import '../styles/Login.css'
import servicePath from '../config/baseUrl'
import axios from 'axios'

const Login = (props) => {

  const [userName, setUserName] = useState('')
  const [password, setPassword] = useState('')
  const [isLoading, setIsLoading] = useState(false)
  // 登录判断
  const checkLogin = () => {
    setIsLoading(true)
    if(!userName) {
      message.error('用户名不能为空 🤒') 
      setTimeout(() => {
        setIsLoading(false)
      }, 500)
      return false
    } else if(!password) {
      message.error('密码不能为空 🤓')
      setTimeout(() => {
        setIsLoading(false)
      }, 500)
      return false
    }
    let dataProps = {
      'userName': userName,
      'password': password,
    }
    axios({
      method: 'post',
      url: servicePath.checkLogin,
      data: dataProps,
      withCredentials: true, // 共享session
    }).then(resp => {
      console.log(resp.data)
      setIsLoading(false)
      if(resp.data.data === '登录成功') {
        localStorage.setItem('openId', resp.data.openId)
        message.success('登录成功 🥳')
        props.history.push('/index')
      } else {
        message.error('用户名或者密码错误')
      }
    })
  }
    
  return (
    <div className="login-div">
      <Spin tip="Loading..." spinning={isLoading}>
        <Card>
          <Input
            id="userName"
            size="large"
            placeholder="Enter your name"
            prefix={<UserOutlined style={{color:'rgba(0,0,0,.25)'}}/>}
            onChange={e => {setUserName(e.target.value)}}
          />
          <br/><br/>
          <Input.Password
            id="pwd"
            size="large"
            placeholder="Enter your password"
            prefix={<KeyOutlined style={{color:'rgba(0,0,0,.25)'}} />}
            onChange={e=> {setPassword(e.target.value)}}
          />
          <br/><br/>
          <Button
            type="primary"
            size="large"
            block
            onClick={checkLogin}
          >登录</Button>
        </Card>
      </Spin>
    </div>
  )
}
export default Login